{% macro selectinput(name, values, value='') -%}
    <select class="form-control" name="{{ name }}" id="{{ name }}">
    {% for v in values %}
        <option value="{{ v }}"  {{ 'selected' if value==v }}>{{ v }}</option>
    {% endfor %}
    </select>
{%- endmacro %}
{% macro checkboxinput(name, checkedvalue, value='',extra='') -%}
    <input type="checkbox" name="{{ name }}" id="{{ name }}" value="{{ checkedvalue }}"  {{ 'checked' if value==checkedvalue }} {{ extra|safe }}>
{%- endmacro %}

{% extends "layout.html" %}
{% block headcenter %}
<table width="100%"><tr><td width="160px">

</td><td><span style="font-size: 24px;">检索 </span><span data-toggle="tooltip" data-placement="bottom" data-html="true" title="
        <p style='text-align: left'><ul style='text-align: left'>
        <li>默认情况下，“检索”界面会随机打开一个项目，您可以从该项目下选择图片进行浏览；此外，您也可以选择自己感兴趣的项目进行浏览。您可以添加一些筛选条件，浏览1000个以内的小图。若您对该项目感兴趣，则可以通过电子邮件的方式向项目管理者来请求对此项目的完整访问权限。
<li>只有公开项目中已完成分类的小图才在此界面可见。
<li>分类树中的丰度统计数据每天更新。
</ul>
</p>"
        class="glyphicon glyphicon-question-sign"></span><br>
<span id="headersubtitle" style="color:#FF6600;"> </span><br>

</td></tr></table>


{% endblock %}

{% block body %}<div id="topbar" >
<table><tr><td>
    <button type="button" class="btn btn-xs btn-primary" onclick="LoadRightPane();" style="width: 260px;">
        <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> 页面刷新</button>

        图片数/页 :
	</td><td style="padding-right: 5px;">{{ selectinput("ipp",['50','100','200','500','1000'],data.ipp) }}
    </td><td style="padding-right: 5px;">缩放 : 
	</td><td style="padding-right: 5px;">{{ selectinput("zoom",['10','20','30','40','50','60','70','80','90','100'],data.zoom) }}
</td><td>
      <label for="magenabled">
      	<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
      </label>

    {{ checkboxinput("magenabled","1",data.magenabled,"style='margin:0px;'") }}
</td><td>&nbsp;

{{ top|safe }}
</td></tr></table>
    </div>
{% include "common/taxopopup.html" %}

<div id="bodycontainer">
  <script>
$(document).ready(function() {
    $("#taxolb").select2({
        ajax: {
            url: "/search/taxo",
            dataType: 'json',
            delay: 250,
            data: function (params) {  return { q: params.term, page: params.page };  },
            processResults: function (data, page) { return { results: data};  },
            cache: true
        },
        minimumInputLength: 3
    }); // Select2 Ajax
    $('#TaxoModal').on('show.bs.modal', function (e) {
         $("#TaxoModalBody").html("加载中...");
         $("#TaxoModalBody").load("/search/taxotree");
    });
    $('[data-toggle="tooltip"]').tooltip();
    $('[data-toggle="popover"]').popover();
    }); // Ready
 </script>
<style> {# On agrandi la taile de la drop down de la popup #}
    UL#select2-taxolb-results {max-height: 500px; }
</style>

       <div id="column-left"  class="" style="position: fixed;	top: 120px;	left: 2px;	bottom: 0px;	width: 260px;
                overflow-y: auto; overflow-x: auto;  margin-bottom: 0px; " >
        <div class="bodyleft" style="margin-left: 2px; width: 231px; margin-top: 3px;">
          <a href='?' class="btn btn-info " style="width: 49%"><span class="glyphicon glyphicon-remove"></span> 清除过滤</a>
           <button class="btn btn-info" style="width: 49%" onclick="LoadRightPane(true);"><span class="glyphicon glyphicon-link"></span> 分享页面</button>
        <br>

 {# Gestion de la selection de Taxonomie Via un Select2 Ajax multiple #}

<div class="filter" style="margin-top: 3px;">
    <button class="btn btn-block btn-xs btn-info left-button" onclick="$('.filter').toggle();">隐藏过滤</button>
</div>
<div class="filter" style="display: none;margin-top: 3px;">
    <button class="btn btn-block btn-xs btn-info left-button" onclick="$('.filter').toggle();">显示过滤</button>
</div>

{# ------- Project ------------#}
<div class="filter ">
	<div class="form-group-sm">
		<label class="title">项目</label>
		<a class="pull-right clear" href='javascript:ClearProjects();'></a>
		<select class="form-control" id="projid" name="projid" style="width: 100%" multiple autocomplete="off"> {{ data.projects_for_select|safe }}</select>
	</div>
</div>

{{ leftb|safe }}

{# ------- Taxo Filter ------------#}
<div >
	<div class="form-group-sm">
		<label class="title">已验证的浮游生物过滤器 &nbsp;</label>
		<a class="pull-right clear" href='javascript:ClearTaxo();'></a>
        <select id="taxolb" multiple="multiple" style="width: 100%"  autocomplete="off"> {{ data.taxo_for_select|safe }} </select>
	</div>
</div>
<div >
{{ checkboxinput("taxochild","1",data.taxochild,"style='margin:0px;'") }} 也显示幼体
</div>

<div class="FilterToggle" style="display:none;cursor:pointer;">
    <span onclick="$('.FilterToggle').toggle();"><span class="glyphicon glyphicon-triangle-right"></span>显示过滤</span>
</div>


<link rel="stylesheet" href="/static/jstree/themes/default/style.min.css" />
<script src="/static/jstree/jstree.min.js"></script>

<style>
    .tree li a {
    padding-right:20px !important;
    background:url(icons/Star-icon.png) top right no-repeat;
}
.tree li.clicked a {
    padding-right:20px !important;
    background:url(icons/Star-icon.png) top right no-repeat #BEEBFF;
}
.tree li a.hover,
.tree li a:hover {
    padding-right:20px !important;
    background:url(icons/Star-icon.png) top right no-repeat #D8F0FA;
}
.taxo_tree_selected .v {background-color: #777777;}
</style>


  <div id="jstreeexp">
      <ul>
    <li>Root node 1</li>
    <li>Root node 2</li>
  </ul>
  </div>

<script>
  $(function () {
    $('#jstreeexp').jstree({
      'core': {
        "animation" : 0,
        "themes" : { "stripes" : false, "icons": false  },
        'data': {
            'dataType': 'JSON',
            'url': '/search/taxotreejson',
            'data': function (node) {
                return {'id': node.id};
            }
        }
      }
    });

      $("#jstreeexp").delegate(".TaxoSel",'click',
          function(o){
            o.preventDefault();
            var id= $(o.target).closest("li").attr("id");
            var valeur= $(o.target).prev().html();
            if($(o.target).hasClass("glyphicon"))
                valeur= $(o.target).parent().prev().html();
           $('#SelectedID').html(id);
           $('#SelectedName').html(valeur);
           $('#taxolb').append($('<option>', {    value: id,    text: valeur}));
            var sel=$("#taxolb").val();
            if(sel==null) sel=[];
            sel.push(id);
            $('#taxolb').val(sel);
            $('#taxolb').change();
          });

    $("#jstree").bind("select_node.jstree", function (e, data) {
        $("#jstree").jstree('open_node', data.node);
    });
    {# Quand on ouvre une branche de l'arbre on met à jours les background pour les nouveaux noeuds  #}
    $("#jstreeexp").on('after_open.jstree', function(){ $('#taxolb').change(); });

    $('#taxolb').change(function (){ {# Mise à jour des background dans l'arbre #}
      $(".taxo_tree_selected").removeClass("taxo_tree_selected");
      var taxofilterarray = [];
      $('#taxolb :selected').each(function(i, selected){ taxofilterarray[i] = "#"+$(selected).val();    });
      $(taxofilterarray.join(",")).addClass("taxo_tree_selected");
    });

  });
</script>



        </div>
    </div>
{#          <div id="column-right" style="position: absolute;top: 150px;left: 270px;bottom: 0px;right: 1px;overflow: auto;"> #}
<style>
.lazy {margin: 15px 5px 0px 5px; }
.ddet {text-align:left;  font-size: 10px; margin-top: -3px;margin-bottom: -1px;  text-decoration: underline; color:#00c;}
.ddets {cursor:pointer;}
#dispfieldlist li a {    padding-top:0px;}
.tooltip-inner { max-width: 500px; }


#column-right {margin-left: 265px;}
#divheadinfo {position:fixed;top:0px;left: 1px;width:100%; height:80px;z-index:12; background-color: #fff;}
#topbar {position:fixed;top:80px;left: 1px;width:100%; height:40px;z-index:10; background-color: #fff;}
body {margin-top: 125px;}
{#Permet de fixer la largeur de la dropdown Taxo Annotation#}
.width240{ width: 240px !important; }
{#Permet de fixer la largeur de la dropdown Sample#}
.width400{ width: 400px !important; }
{#Permet de reduire la taille et l'espace du texte du dropdown Taxo Annotation#}
#select2-taxolbanno-results li {font-size: 12px; padding: 3px;}
.popover {max-width: 500px;}

</style>
<script>
var PrevTxtFilter="INITIAL"
function LoadRightPane(NoAjax){
    var TxtFilter=""
    req={taxo:$("#taxolb").val(),resultwidth:$("#column-right").width(),windowheight:$(window).height()};
    var taxofilterarray = [];
    $('#taxolb :selected').each(function(i, selected){ taxofilterarray[i] = $(selected).text();    });
    req['taxochild']=$("#taxochild").prop("checked")?"1":"0";
    if(taxofilterarray.length>0) {
        TxtFilter += " Taxo=" + (taxofilterarray.join(","));
        if (req['taxochild'] == "1") TxtFilter += "(with childs)";
    }
    req['ipp']=$("#ipp").val();
    req['zoom']=$("#zoom").val();
    req['magenabled']=$("#magenabled").prop("checked")?"1":"0";

    req['MapN']=$("#filt_MapOutN").val();
    req['MapW']=$("#filt_MapOutW").val();
    req['MapE']=$("#filt_MapOutE").val();
    req['MapS']=$("#filt_MapOutS").val();
    if((req['MapN']!="")&&(req['MapW']!="")&&(req['MapE']!="")&&(req['MapS']!=""))
        TxtFilter+=" Position=("+req['MapN']+","+req['MapW']+","+req['MapE']+","+req['MapS']+")"
    else {delete req['MapN']; delete req['MapW'];delete req['MapE']; delete req['MapS']; }

    req['depthmin']=$("#filt_depthmin").val();
    req['depthmax']=$("#filt_depthmax").val();
    if((req['depthmin']!="")&&(req['depthmax']!=""))
        TxtFilter+=" Depth in("+req['depthmin']+"-"+req['depthmax']+")";
    else {delete req['depthmin']; delete req['depthmax']; }

    if($('#sampleid').val()!=null)
      req['samples']=String($('#sampleid').val())
    else req['samples']="";
    if(req['samples']!="")
        TxtFilter+=" Samples="+$.map( $('#sampleid  option:selected'), function (element) { return $(element).text() }).join(', ');
    req['instrum']=$("#filt_instrum").val();
    if(req['instrum']!="")
        TxtFilter+=" Instrument ="+req['instrum'];
    var jqmonth=$('#month');
    if(jqmonth.val()!=null) {
      req['month'] = String(jqmonth.val());
      TxtFilter += " Month=" + $.map(jqmonth.find('option:selected'), function (element) {
            return $(element).text()
          }).join(', ');
    }

    if($('#projid').val()!=null)
      req['projid']=String($('#projid').val())
    else req['projid']="";
    if(req['projid']!="")
        TxtFilter+=" Project="+$.map( $('#projid  option:selected'), function (element) { return "<a href='/prj/"+$(element).val()+"'>"+$(element).text()+"</a>" }).join(', ');

    req['fromdate']=$("#filt_fromdate").val();
    if(req['fromdate']!="")
        TxtFilter+=" Date >= "+req['fromdate'];
    else delete req['fromdate'];

    req['todate']=$("#filt_todate").val();
    if(req['todate']!="")
        TxtFilter+=" Date <= "+req['todate'];
    else delete req['todate'];

    req['fromtime']=$("#filt_fromtime").val();
    if(req['fromtime']!="")
        TxtFilter+=" Time >= "+req['fromtime'];
    else delete req['fromtime'];

    req['totime']=$("#filt_totime").val();
    if(req['totime']!="")
        TxtFilter+=" Time <= "+req['totime'];
    else delete req['totime'];

    req['inverttime']=$("#filt_inverttime").prop("checked")?"1":"";
    if(req['inverttime']=="1")
        TxtFilter+=" Time Invert ";
    else delete req['inverttime'];
    var jqdaytime=$('#daytime');
    if(jqdaytime.val()!=null) {
      req['daytime'] = String(jqdaytime.val());
      TxtFilter+=" DayTime="+$.map(jqdaytime.find('option:selected'), function (element) { return $(element).text() }).join(', ');
    }


    $(".zoomtracker,.zoomstatus,.magnifyarea,.cursorshade").remove();
    if(TxtFilter!="")
        TxtFilter="Filter: "+TxtFilter
    if(NoAjax==true) {
        delete req["resultwidth"];
        delete req["windowheight"];
        var urlparam={};
        for	(var k in req)
{#            if(req[k]!=="") // Il faut tous les laisser pour pouvoir forcer leur effacement par rapport aux users settings  #}
                urlparam[k]=req[k];
        {#      window.location="?"+$.param(urlparam);  Version ouvrant dans une popup#}
        var url=window.location.protocol+"//"+window.location.host+"/explore/?"+$.param(urlparam);
        window.location="mailto:?subject=Ecotaxa%20page%20share&body="+encodeURIComponent("Hello,\n\nAn Ecotaxa user want share this page with you \n"+url);
        return;
    }
    $("#column-right").html("<img src='/static/spinningred.gif'> Loading");
    $("#column-right").load("/explore/LoadRightPane",req);
    $('#headersubtitle').html(TxtFilter);
}


$(document).ready(function() {
    if ("{{data.sortorder}}"=="desc")
        SortToggle();
    $('#statuslabelspan').popover({html:true,trigger:'hover',placement:"left",container: 'body'});
    $('#statusfilter').data('content',$('#statuslabelspan').data('content'))
    $('#statusfilter').popover({html:true,trigger:'hover',placement:"left",container: 'body'});
    $("#taxofilter").val("");


    $("#projid").select2({
        ajax: {
            url: "/search/exploreproject",
            dataType: 'json',
            delay: 250,
            data: function (params) {  return { q: params.term   };  },
            processResults: function (data, page) { return { results: data};  },
            cache: true
        },
        dropdownCssClass:"width400"
    }); // Select2 Ajax

});
function ClearProjects(){
  $( "#projid" ).val(null).trigger("change");
}
function ClearTaxo(){
  $( "#taxolb" ).val(null).trigger("change");
}

function PostAddImages(){
        $(document).scrollTop(0);
        // Required to  have Select2 component working on Bootstrap Popup
        $.fn.modal.Constructor.prototype.enforceFocus = function() {};
        // Add Zoom
        jQuery('div#column-right img.lazy').Lazy({bind: 'event',afterLoad: function(element) {
            if($('#magenabled').prop("checked")==false)
                return; // Si il y a une checkbox magenabled et qu'elle est decochée on ne met pas le zoom
            AddZoom(element);}});
        // Enable the popover
        var option={'trigger':'hover','html':true};
        $('div.subimg').popover(option);
        $('.ddets').click(function(e){
            e.stopPropagation();
            var url="/objectdetails/"+$(e.target).closest('td').find('img').prop('id').substr(1)+"?w="+($(window).width()-400)+"&h="+($(window).height()-40)+"&ajax=1";
            var options={}
            $("#PopupDetails .modal-content").html("Loading...");

            $('#PopupDetails .modal-lg').css('width',$(window).width()-40);
            $('#PopupDetails').modal(options);
            $("#PopupDetails .modal-content").load(url);
            });
$('#PopupDetails').on('hidden.bs.modal', function (e) {
    $("#PopupDetails .modal-content").html("CLEAN");
    $(".zoomContainer").remove();
})

}  //PostAddImages

function ClearAllFilterCriteria(){
    ClearCoord();
    ClearDates();
    ClearTimes();
    ClearSamples();
    ClearInstrum();
    ClearDepths();
    LoadRightPane();
}
</script>
        <div id="column-right" >
            RIGHT
            {% if right=='dodefault' %}
                <script>
                $(document).ready(function() {
                        LoadRightPane();
                       }); // Ready
                 </script>
                Loading ....
            {% else %}
                {{ right|safe }}
            {% endif %}
		</div>
    </div> {# Container #}

<div id="PopupDetails" class="modal " tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      ...
    </div>
  </div>
</div>

{% endblock %}